<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实现超出整数存储范围的两个大正整数相加</title>
</head>
<body>
  <div>
    A: <input type="number" id="a">
  </div>
  <div>
    B: <input type="number" id="b">
  </div>
  <p>和为：<span></span></p>
  <script>
    let a = document.querySelector('#a'),
      b = document.querySelector('#b'),
      span = document.querySelector('span');
    a.oninput = debounce(() => {
      let value = a.value;
      let valueB = b.value;
      if(value && valueB) {
        span.innerHTML = addStr(value, valueB)
      }
    }, 500)
    b.oninput = debounce(() => {
      let value = a.value;
      let valueB = b.value;
      if(value && valueB) {
        span.innerHTML = addStr(value, valueB)
      }
    }, 500)
    function debounce(callback, time) {
      let timer = null;
      return function() {
        if(timer) clearTimeout(timer);
        timer = setTimeout(() => {
          callback()
        }, time)
      }
    }
    function addStr(a, b) {
      let lenA = a.length,
        lenB = b.length;
      for(let i = 0; i < Math.abs(lenA - lenB); i++) { //Math.abs() 取绝对值
        if(lenA > lenB) b = '0' + b;
        if(lenA < lenB) a = '0' + a;
      }
      let arrA = a.split('').reverse(),
        arrB = b.split('').reverse();
      const arrSum = arrA.map(item => 0);
      for(let n = 0; n < arrA.length; n++) {
        let currentSum = parseInt(arrA[n]) + parseInt(arrB[n])  + arrSum[n];
        if(currentSum > 9) {
          arrSum[n] = currentSum - 10;
          arrSum[n + 1] = 1;
        } else {
          arrSum[n] = currentSum;
        }
      }
      return arrSum.reverse().join('');
    }
  </script>
</body>
</html>